import React, { Component } from 'react'
import style from './Item.module.css'

export class Item extends Component {

  state = {
    mouse: false
  }
  // 鼠标滑入滑出事件
  handleMouse = (flag) => {
    return () => {
      this.setState({ mouse: flag })
    }
  }
  // 删除当前todo
  delTodo = (id) => {
    if (window.confirm('你确定删除吗？')) {
      this.props.delTodo(id) //触发list方法
    }
  }
  // 勾选、取消勾选
  changeTodo = (event, id) => {
    // console.log('changeTodo', event.target.checked, id);
    this.props.changeTodo(id, event.target.checked)//触发list方法
  }


  render() {
    const { id, name, done } = this.props
    const { mouse } = this.state
    return (
      <div className={style.item} style={{ backgroundColor: mouse ? '#ddd' : '#fff' }} onMouseEnter={this.handleMouse(true)} onMouseLeave={this.handleMouse(false)}>
        {/* defaultChecked是初始值，后续可以改；但checked设置后就会变成只读的，后续就无法改变了 */}
        <input type="checkbox" checked={done} onChange={(event) => this.changeTodo(event, id)} />
        <span className={style.title}>{name}</span>
        <button className={style.del} style={{ display: mouse ? 'block' : 'none' }} onClick={() => this.delTodo(id)}>删除</button>
      </div>
    )
  }
}

export default Item
